<template>
  <el-dialog
    v-model="visible"
    title="批量推理"
    width="1000px"
    :close-on-click-modal="false"
  >
    <div class="batch-infer-content">
      <!-- 推理前 -->
      <div v-if="!inferResult" class="before-infer">
        <div class="info-section">
          <p>已选择 <strong>{{ selectedIds.length }}</strong> 条疑似资产进行批量推理</p>
          <el-checkbox v-model="forceReinfer" style="margin-top: 10px">
            强制重新推理（已推理的也会重新推理）
          </el-checkbox>
        </div>
      </div>

      <!-- 推理结果 -->
      <div v-else class="infer-result">
        <div class="result-summary">
          <el-descriptions :column="4" border>
            <el-descriptions-item label="总数">
              <span class="summary-value">{{ inferResult.total }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="成功">
              <span class="summary-value success">{{ inferResult.success }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="失败">
              <span class="summary-value danger">{{ inferResult.failed }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="跳过">
              <span class="summary-value info">{{ inferResult.skipped }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="result-list">
          <el-table :data="inferResult.results" border stripe max-height="400">
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.success ? 'success' : 'danger'" size="small">
                  {{ row.success ? "成功" : "失败" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="消息" min-width="200" />
            <el-table-column label="推理结果" min-width="250">
              <template #default="{ row }">
                <div v-if="row.success && row.primary_department">
                  <div class="department-name">{{ row.primary_department }}</div>
                  <div class="confidence-value">
                    置信度: {{ row.primary_confidence }}%
                  </div>
                </div>
                <span v-else class="no-data">-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" fixed="right">
              <template #default="{ row }">
                <template v-if="row.success">
                  <el-button
                    v-if="row.inference_status !== 'confirmed' && row.inference_status !== 'rejected'"
                    size="small"
                    type="success"
                    @click="handleConfirm(row)"
                  >
                    确认
                  </el-button>
                  <el-button
                    v-if="row.inference_status !== 'confirmed' && row.inference_status !== 'rejected'"
                    size="small"
                    type="warning"
                    @click="handleReject(row)"
                  >
                    拒绝
                  </el-button>
                  <el-tag
                    v-if="row.inference_status === 'confirmed'"
                    type="success"
                    size="small"
                  >
                    已确认
                  </el-tag>
                  <el-tag
                    v-if="row.inference_status === 'rejected'"
                    type="danger"
                    size="small"
                  >
                    已拒绝
                  </el-tag>
                </template>
                <span v-else class="no-action">-</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button v-if="!inferResult" @click="handleCancel">取消</el-button>
      <el-button
        v-if="!inferResult"
        type="primary"
        :loading="inferring"
        @click="handleInfer"
      >
        开始推理
      </el-button>
      <el-button v-else type="primary" @click="handleClose">关闭</el-button>
    </template>

    <!-- 确认弹窗 -->
    <ConfirmModal
      v-model="confirmVisible"
      :asset-id="currentAssetId"
      :department="currentDepartment"
      @confirm="handleConfirmSubmit"
    />

    <!-- 拒绝弹窗 -->
    <RejectModal
      v-model="rejectVisible"
      :asset-id="currentAssetId"
      :department="currentDepartment"
      @reject="handleRejectSubmit"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { batchInferSuspectedAssets } from "../../../servers";
import ConfirmModal from "./ConfirmModal.vue";
import RejectModal from "./RejectModal.vue";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  selectedIds: { type: Array<number>, default: () => [] },
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "refresh"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const forceReinfer = ref(false);
const inferring = ref(false);
const inferResult = ref<any>(null);

// 确认和拒绝相关
const confirmVisible = ref(false);
const rejectVisible = ref(false);
const currentAssetId = ref<number | null>(null);
const currentDepartment = ref<string>("");

// 开始推理
const handleInfer = async () => {
  if (props.selectedIds.length === 0) {
    ElMessage.warning("请先选择要推理的资产");
    return;
  }

  inferring.value = true;
  try {
    const { data } = await batchInferSuspectedAssets({
      ids: props.selectedIds,
      force: forceReinfer.value,
    });

    if (data) {
      inferResult.value = data;
      ElMessage.success("批量推理完成");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "批量推理失败");
  } finally {
    inferring.value = false;
  }
};

// 确认
const handleConfirm = (row: any) => {
  currentAssetId.value = row.id;
  currentDepartment.value = row.primary_department || "";
  confirmVisible.value = true;
};

// 拒绝
const handleReject = (row: any) => {
  currentAssetId.value = row.id;
  currentDepartment.value = row.primary_department || "";
  rejectVisible.value = true;
};

// 确认提交
const handleConfirmSubmit = () => {
  // 更新当前结果状态
  if (inferResult.value && currentAssetId.value) {
    const result = inferResult.value.results.find(
      (r: any) => r.id === currentAssetId.value
    );
    if (result) {
      result.inference_status = "confirmed";
    }
  }
  // 刷新列表
  emit("refresh");
};

// 拒绝提交
const handleRejectSubmit = () => {
  // 更新当前结果状态
  if (inferResult.value && currentAssetId.value) {
    const result = inferResult.value.results.find(
      (r: any) => r.id === currentAssetId.value
    );
    if (result) {
      result.inference_status = "rejected";
    }
  }
  // 刷新列表
  emit("refresh");
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};

// 关闭
const handleClose = () => {
  inferResult.value = null;
  forceReinfer.value = false;
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.batch-infer-content {
  .before-infer {
    .info-section {
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }

  .infer-result {
    .result-summary {
      margin-bottom: 20px;

      .summary-value {
        font-weight: 500;
        font-size: 16px;

        &.success {
          color: #67c23a;
        }

        &.danger {
          color: #f56c6c;
        }

        &.info {
          color: #909399;
        }
      }
    }

    .result-list {
      .department-name {
        font-weight: 500;
        color: #303133;
        margin-bottom: 4px;
      }

      .confidence-value {
        font-size: 12px;
        color: #909399;
      }

      .no-data,
      .no-action {
        color: #909399;
        font-size: 12px;
      }
    }
  }
}
</style>

